package eproject.mm.com.projectsupervision.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.suke.widget.SwitchButton;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;
import eproject.mm.com.projectsupervision.widget.CustomDatePicker;
import org.w3c.dom.Text;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import eproject.mm.com.projectsupervision.BuildConfig;
import eproject.mm.com.projectsupervision.PrjApplication;
import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.adapter.PassengerAdapter;
import eproject.mm.com.projectsupervision.widget.IconFontTextview;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ProblemDealActivity extends Activity {
    private static final String TAG = ProblemDealActivity.class.getName();

    public static final String TYPE = "application/octet-stream";

    ImageView iv_takePhoto;

    RecyclerView rv_photos;
    PassengerAdapter passengerAdapter;
    ArrayList imageUrls;

    RelativeLayout rl_checkOk;
    RelativeLayout rl_limitDate;
    SwitchButton sb_checkOk;
    TextView tv_dealIntroLabel;
    EditText et_intro;
    TextView tv_date;

    private OkHttpClient client;
    CustomDatePicker customDatePicker;

    String imageFilePath,imageFileName;
    TextView tv_title;

    String type,problemId;
    IconFontTextview iftv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_problem_deal);

        Intent intent = getIntent();
        Bundle bundleFragment = intent.getExtras();
        type = bundleFragment.getString("type");
        problemId = bundleFragment.getString("problemid");

        initView();
        loadData();

        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();

        iftv_back = (IconFontTextview)findViewById(R.id.iftv_back);
        iftv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    public void initView(){
        rv_photos = (RecyclerView)findViewById(R.id.rv_photos);
        et_intro = (EditText) findViewById(R.id.et_intro);
        et_intro.setHintTextColor(Color.GRAY);

        tv_date = (TextView) findViewById(R.id.tv_date);
        rl_checkOk = (RelativeLayout) findViewById(R.id.rl_checkOk);
        rl_limitDate = (RelativeLayout) findViewById(R.id.rl_limitDate);
        sb_checkOk = (SwitchButton) findViewById(R.id.sb_checkOk);
        tv_dealIntroLabel = (TextView) findViewById(R.id.tv_dealIntroLabel);
        tv_title = (TextView) findViewById(R.id.tv_title);

        initDatePicker();

        sb_checkOk.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton buttonView, boolean isChecked) {
                if(isChecked){
                    rl_limitDate.setVisibility(View.GONE);
                }else{
                    rl_limitDate.setVisibility(View.VISIBLE);
                }
            }
        });

        if(type.equals("0")){//整改情况提交
            rl_checkOk.setVisibility(View.GONE);
            rl_limitDate.setVisibility(View.GONE);
        }else if(type.equals("1")){//复查结果提交
            tv_title.setText("复查结果提交");
            tv_dealIntroLabel.setText("复查情况");
            et_intro.setHint("输入整改复查情况");
        }
    }

    private void loadData(){
        imageUrls = new ArrayList();
        imageUrls.add("hehe");

        passengerAdapter = new PassengerAdapter(this, imageUrls);

        rv_photos.setLayoutManager(new GridLayoutManager(this, 4) {
            @Override
            public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
                super.onMeasure(recycler, state, widthSpec, heightSpec);
            }
        });

        rv_photos.getLayoutManager().setAutoMeasureEnabled(true);
        rv_photos.setAdapter(passengerAdapter);

        passengerAdapter.setOnItemClickLitener(new PassengerAdapter.OnItemClickLitener() {
            @Override
            public void onBigClick(int position) {
                if (position==imageUrls.size()-1) {

                    String name = new SimpleDateFormat("yyyyMMddhhmmssSSS").format(new Date());

                    //File outputImage = new File(getExternalCacheDir(),name+".jpg");
                    File outputImage = new File(Environment.getExternalStorageDirectory(),name+".jpg");
                    imageFilePath = outputImage.getPath();

                    android.net.Uri imageUri;
                    if(outputImage.exists())
                    {
                        outputImage.delete();
                        try
                        {
                            outputImage.createNewFile();
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                    }
                    imageFileName = outputImage.getName();
                    if (Build.VERSION.SDK_INT>=24)
                    {
                        //imageUri = FileProvider.getUriForFile(ReportActivity.this,"eproject.mm.com.projectsupervision.fileProvider",outputImage);
                        imageUri = FileProvider.getUriForFile(ProblemDealActivity.this, BuildConfig.APPLICATION_ID+".provider",outputImage);

                    }else{
                        imageUri = Uri.fromFile(outputImage);
                        imageFilePath = imageUri.getPath();
                    }

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                        if ((ContextCompat.checkSelfPermission(ProblemDealActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)||
                                (ContextCompat.checkSelfPermission(ProblemDealActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
                            //如果没有授权，则请求授权
                            ActivityCompat.requestPermissions(ProblemDealActivity.this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                        } else {
                            //有授权，直接开启摄像头
                            //6.0 camera

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (intent.resolveActivity(getPackageManager())!=null){
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                                startActivityForResult(intent, 1);
                            }
                        }

                    }else{
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                        intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        startActivityForResult(intent,1);
                    }
                }

            }
            @Override
            public void onSmallClick(int position) {
                imageUrls.remove(position);
                passengerAdapter.notifyItemRemoved(position);
            }
        });
    }
    private void initDatePicker() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        String now = sdf.format(new Date());
        tv_date.setText(now.split(" ")[0]);

        customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv_date.setText(time.split(" ")[0]);
            }
        }, "2010-01-01 00:00", "2020-12-31 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 不显示时和分
        customDatePicker.setIsLoop(false); // 不允许循环滚动
    }
    public  void onDateSelectClick(View view){
        customDatePicker.show(tv_date.getText().toString());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1){
            if(resultCode == RESULT_OK){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imageUrls.add(0,imageFilePath);
                        //更新第一个位置的图片
                        passengerAdapter.notifyItemInserted(0);
                    }
                });
            }
        }
    }

    public void onSubmit(View view){
        if(et_intro.getText().toString().trim().equals("")){
            if(type.equals("0")){//整改情况提交
                Toast.makeText(this,"请输入整改情况",Toast.LENGTH_SHORT).show();
            }else if(type.equals("1")){//复查结果提交
                Toast.makeText(this,"请输入复查情况",Toast.LENGTH_SHORT).show();
            }

            return;
        }
        final LoadingDialog loadingDialog = new LoadingDialog(this);
        loadingDialog.setLoadingText("加载中...")//设置loading时显示的文字
                .show();

        MultipartBody.Builder builder = new MultipartBody.Builder();

        for(int i=0; i < imageUrls.size()-1; i++) {
            String filePath = (String)imageUrls.get(i);
            File imageFile = new File(filePath);
            RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), imageFile);
            builder.addFormDataPart("files", imageFile.getName(), fileBody);
        }

        String action = "";
        if(type.equals("0")){
            action = "problemDealSubmit";
            builder.addFormDataPart("describes",et_intro.getText().toString());
            builder.addFormDataPart("queid",problemId);
        }else if(type.equals("1")){
            action = "problemCheckSubmit";
            builder.addFormDataPart("describes",et_intro.getText().toString());
            builder.addFormDataPart("queid",problemId);
            if(sb_checkOk.isChecked()){
                builder.addFormDataPart("status","1");
            }else{
                builder.addFormDataPart("status","0");
            }
            builder.addFormDataPart("limitdate",tv_date.getText().toString());
        }

        RequestBody requestBody = builder.build();
        Request.Builder okbuilder = new Request.Builder();
        okbuilder.addHeader("authenticationToken", PrjApplication.getInstance().getAuthenticationToken());
        Request requestPostFile = okbuilder
                .url("http://"+ PrjApplication.getInstance().getServerIp() +":"+PrjApplication.getInstance().getServerPort()+"/"+PrjApplication.getInstance().getPreFixPath()+"/"+action)
                .post(requestBody)
                .build();
        client.newCall(requestPostFile).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                loadingDialog.close();
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.close();
                        ProblemDealActivity.this.finish();
                    }
                });
            }
        });
    }
}
